<template>
  <div id="dishBox">
    <div id="title">
        <h3>菜品管理</h3>
    </div>
    <div class="blackLine"></div>
    <div id="abilityBox">
        <el-button class="abilityBt" type="primary" plain @click="openAddForm()">添加菜品</el-button>
        <el-tooltip class="item" effect="dark" content="导入格式为:xlsx" placement="top">
            <el-button class="abilityBt" type="primary" plain>批量导入</el-button>
        </el-tooltip>
        <el-button class="abilityBt" type="primary" plain @click="exportDish()">批量导出</el-button>
        <el-button :disabled="this.isSelectBtn" class="abilityBt" type="danger" plain @click="deleteSelectItem()">批量删除</el-button>
        <div id="selsctBox">
            <el-select v-model="searchParam.categoryId" placeholder="请选择类别搜索" id="selectCategory" size="mini" visible-change="false"	clearable>
                <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
        </div>
        
    </div>
    <div id="dishTableBox">
        <el-table
            :default-sort="{prop: 'sort', order: 'descending'}"
            ref="filterTable"
            @select="selectCheck"
            @selection-change="handleSelectionChange"
            :highlight-current-row="true"
            :stripe="true"
            :border="true"
            :data="tableData"
            style="width: 100%">
            <el-table-column
                type="selection"
                width="40">
            </el-table-column>
            <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="菜品标签:">
                        <span>{{ props.row.tag }}</span>
                    </el-form-item>
                    <el-form-item label="菜品图片:">
                        <span class="demonstration">{{ fit }}</span>
                        <el-image
                            style="width: 100px; height: 100px"
                            :src="props.row.img"
                            :fit="fit"></el-image>
                    </el-form-item>
                    <el-form-item label="菜品描述:">
                        <span>{{ props.row.description }}</span>
                    </el-form-item>
                    <el-form-item label="创建时间:">
                        <span>{{ props.row.createTime }}</span>
                    </el-form-item>
                    <el-form-item label="更新时间:">
                        <span>{{ props.row.updateTime }}</span>
                    </el-form-item>
                    <el-form-item label="创建者:">
                        <span>{{ props.row.createUser }}</span>
                    </el-form-item>
                    <el-form-item label="更新者:">
                        <span>{{ props.row.updateUser }}</span>
                    </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column
                width="200"
                align="center"
                label="ID"
                prop="id">
            </el-table-column>
            <el-table-column
                column-key="categoryName"
                :filters="[{text: '肉类', value: '肉类'}, {text: '2016-05-02', value: '2016-05-02'}, {text: '2016-05-03', value: '2016-05-03'}, {text: '2016-05-04', value: '2016-05-04'}]"
                :filter-method="filterHandler"
                width="90"
                align="center"
                label="菜品类别"
                prop="categoryName">
            </el-table-column>
            <el-table-column
                width="150"
                align="center"
                label="名称"
                prop="name">
            </el-table-column>
            <el-table-column
                width="110"
                align="center"
                label="价格"
                prop="price">
            </el-table-column>
            <el-table-column
                width="80"
                align="center"
                label="状态"
                prop="state">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.state === 0? 'success':'danger'">{{scope.row.state == 0? '在售':'下架'}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                sortable
                width="80"
                align="center"
                label="排序"
                prop="sort">
            </el-table-column>
            <el-table-column
                align="center">
                <template slot="header" slot-scope="scope">
                    <el-input
                        id="searchByName"
                        v-model="searchParam.name"
                        size="mini"
                        placeholder="输入菜品名称搜索">
                        <!-- <template #append>
                            <i class="el-icon-search"></i>
                        </template> -->
                    </el-input>
                    <el-button @click="findDish()" id="searchBtn" icon="el-icon-search" circle></el-button>
                </template>
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="openEditForm(scope.row.id)">编辑</el-button>
                    <el-button
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)">详情</el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="deletedDish(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div id="footBox">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="this.pageParam.currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="this.pageParam.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageParam.tableDataTotal">
            </el-pagination>
        </div>
    </div>
    <el-dialog
        :show-close="false"
        :close-on-click-modal="false"
        :title="this.isEditForm == true ? '编辑菜品':'添加菜品'"
        :visible.sync="centerDialogVisible"
        width="50%"
        center>
        <el-form :rules="rules" ref="form" :model="addFormData" label-width="80px">
            <el-form-item label="菜品名称" prop="name">
                <el-input maxlength="10" minlength="2" v-model="addFormData.name" id="nameInput"></el-input>
            </el-form-item>
            <el-form-item label="菜品类别" prop="categoryId">
                <el-select v-model="addFormData.categoryId" placeholder="请选择类别" >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="菜品价格">
                <el-input-number v-model="addFormData.price" :precision="2" controls-position="right"  :min="1" :max="3000" />
            </el-form-item>
            <el-form-item label="菜品排序">
                <el-input-number v-model="addFormData.sort" controls-position="right"  :min="0" :max="200" />
            </el-form-item>
            <el-form-item label="菜品状态">
                <el-radio-group v-model="addFormData.state">
                    <el-radio :label='0'>在售</el-radio>
                    <el-radio :label='1'>停售</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="菜品标签">
                <div id="tagbox">
                    <el-tag
                        :key="tag"
                        v-for="tag in addFormData.tag"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(tag)">
                        {{tag}}
                    </el-tag>
                    <el-input
                        class="input-new-tag"
                        v-if="inputVisible"
                        v-model="inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm"
                        >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                </div>
            </el-form-item>
            <el-form-item label="菜品图片" prop="img">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:8888/hwy/cater/file/upload"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="addFormData.img" :src="addFormData.img" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="菜品描述">
                <el-input
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="addFormData.description"
                    maxlength="2000"
                    show-word-limit
                    >
                </el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeAddForm()">取 消</el-button>
            <el-button type="primary"  @click="sendDish('form')">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    data(){
        //验证菜品名称字段
        var validateName = (rule, value, callback) =>{
            //中文验证
            let reg = /[^\u4e00-\u9fa5]/;;
            let name = value;
            if ( reg.test(name) || name=='') {
                callback(new Error('菜名必须为中文'))
            }else{
                callback();
            }
        }
        //验证图片
        var validateImg = (rule, value, callback) =>{
            console.log("图片验证："+value)
            if ( value == '') {
                callback(new Error('图片不能为空'))
            }else{
                callback();
            }
        }
        return{
            //表单验证
            rules: {
                name: [
                    { validator: validateName, trigger: 'blur'},
                    { min: 2, max: 10, message: "长度在 2 到 10个字符", trigger: "blur" },
                ],
                img: [
                    { validator: validateImg, trigger: 'blur' },
                ],
                categoryId : [
                    { 
                        required: true,
                        message: "类别不能为空",
                        trigger: "blur"
                    }
                ]
            },
            //批量删除按钮是否禁用
            isSelectBtn: true,
            //被多选的数据
            selectData:[],
            //editData数据的菜品id
            editDishId:'',
            //是否将addForm改变为editForm页面
            isEditForm : false,
            inputVisible: false,
            inputValue: '',
            //addform的菜品类别选择器
            options: [],
            value: '',
            //添加菜品弹窗是否显现
            centerDialogVisible: false,
            //addForm数据
            addFormData: {
                categoryId: '',
                name: '',
                price: '',
                img: '',
                description: '',
                state: 0,
                sort: '',
                tag: [],
            },
            //表格数据
            tableData: [],
            //查询参数
            searchParam:{
                name:"",
                categoryId: "",
            },
            //分页
            pageParam:{
                //当前第几页
                currentPage: 1,
                //数据总条数
                tableDataTotal: 0,
                //每页条数
                onePageSize: 10,
            },
        }
    },
    methods: {
        //过滤方法
        filterHandler(value, row, column) {
            console.log(value)
            const property = column['property'];
            return row[property] === value;
        },
        //用户导出
        exportDish(){
            window.open("http://localhost:8888/hwy/cater/dish/exportDish",'_self');
        },
        //当勾选表格多选框时
        selectCheck(selection, row){
            // console.log(selection+','+row)
        },
        //批量删除
        deleteSelectItem(){
            this.$confirm("此操作将永久删除这些菜品, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(()=>{
                this.$axios.post("http://localhost:8888/hwy/cater/dish/deleteSelect",this.selectData)
                    .then((response) => {
                        if (response.data.code === 1 ) {
                            this.$message({
                                message: response.data.data,
                                type: 'success',
                            });
                        } else {
                            this.$message({
                                message: response.data.msg,
                                type: 'error',
                            });
                        }
                        this.findDish();
                    })
            }).catch(()=>{
                this.$message({
                    type: "info",
                    message: "已取消删除",
                });
            })

        },
        //每页条数改变
        handleSizeChange(val) {
            this.pageParam.onePageSize = val;
            this.findDish();
        },
        //改变页码
        handleCurrentChange(val) {
            this.pageParam.currentPage = val;
            this.findDish();
        },
        //删除菜品
        deletedDish(id){
            this.$confirm("此操作将永久删除该菜品, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
            .then(() => {
                this.$axios.post("http://localhost:8888/hwy/cater/dish/deletedDish/"+id)
                        .then((response) => {
                            if (response.data.code === 1 ) {
                                this.$message({
                                    message: response.data.data,
                                    type: 'success',
                                });
                            } else {
                                this.$message({
                                    message: response.data.msg,
                                    type: 'error',
                                });
                            }
                            this.findDish();
                        })
            })
            .catch(() => {
                this.$message({
                    type: "info",
                    message: "已取消删除",
                });
            });
        },
        //将editForm改为addForm
        closeEditForm(){
            this.isEdoitForm = false;
            this.editDishId = '';
        },
        //改变addForm为editForm并打开
        openEditForm(id){
            this.editDishId = id;
            this.isEditForm = true;
            this.centerDialogVisible = true;
            //根据菜品id查具体菜品信息，并显现出来
            this.$axios.get("http://localhost:8888/hwy/cater/dish/getByIdDish/"+id)
                    .then((response) => {
                        // console.log(response)
                        this.addFormData = response.data.data;
                        this.addFormData.tag = response.data.data.tag.split(',');
                        // console.log(this.addFormData)
                    })
        },
        //添加菜品或更改菜品
        sendDish(ruleForm){
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    if (this.isEditForm == true) {
                        // console.log("走编辑")
                        //这句报错应该是因为传过去时是数组转字符串，而编辑时从后台接收到的已经是空字符串了
                        this.addFormData.tag = this.addFormData.tag.join(",");
                        this.$axios.post("http://localhost:8888/hwy/cater/dish/editDish/"+this.editDishId,this.addFormData)
                            .then((response) => {
                                // console.log(response.data.data)
                                this.$message({
                                    message: response.data.data,
                                    type: 'success',
                                });
                                this.closeAddForm();
                            })
                    }else{
                        this.addFormData.tag = this.addFormData.tag.join(",");
                        this.$axios.post("http://localhost:8888/hwy/cater/dish/addDish",this.addFormData)
                            .then((response) => {
                                // console.log(response.data.data)
                                this.$message({
                                    message: response.data.data,
                                    type: 'success',
                                });
                                this.closeAddForm();
                            })
                    }
                } else {
                    this.$message({
                        message: '添加失败。',
                        type: 'error'
                    });
                    return false;
                }    
            });
        },
        //关闭添加页面
        closeAddForm(){
            console.log("关闭添加页面")
            if (this.isEditForm == true){
                this.isEditForm = false;
                // console.log(this.isEdoitForm)
                this.addFormData.id = '';
                this.addFormData.createTime = '';
                this.addFormData.updateTime = '';
                this.addFormData.createUser = '';
                this.addFormData.updateuser = '';
            }
            this.centerDialogVisible = false;
            this.clearAddForm();
            this.findDish();
        },
        //清空addForm表数据
        clearAddForm(){
            this.addFormData.categoryId = '';
            this.addFormData.name = '';
            this.addFormData.price = '';
            this.addFormData.img = '';
            this.addFormData.description = '';
            this.addFormData.status = 0;
            this.addFormData.sort = '';
            this.addFormData.tag = [];
        },
        //打开addForm页面时查询菜品分类列表
        findDetailCategory(){
            this.$axios.post("http://localhost:8888/hwy/cater/category/findDetailCategory/1")
                    .then((response) => {
                        // console.log(response.data.data)
                        this.options = response.data.data;
                    })
        },
        //关闭标签
        handleClose(tag) {
            this.addFormData.tag.splice(this.addFormData.tag.indexOf(tag), 1);
        },
        showInput() {
            this.inputVisible = true;
            this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
            });
        },

        handleInputConfirm() {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.addFormData.tag.push(inputValue);
            }
            this.inputVisible = false;
            this.inputValue = '';
        },
        //打开添加次菜品页面
        openAddForm(){
            this.centerDialogVisible = true;
            // this.clearAddForm();
            this.findDetailCategory();
            // console.log("add时的tag："+this.addFormData.tag)
        },
        //查询所有菜品
        findDish(){
            this.$axios.post("http://localhost:8888/hwy/cater/dish/findDish/"+this.pageParam.currentPage+"/"+this.pageParam.onePageSize,this.searchParam)
                    .then((response) => {
                        this.tableData = response.data.data.dishData;
                        this.pageParam.tableDataTotal = response.data.data.page.total;
                        this.pageParam.currentPage = response.data.data.page.current;
                    })
        },
        //多选表行
        handleSelectionChange(val) {
            this.selectData = val;
            // console.log(this.selectData)
        },
        //addForm图片回显
        handleAvatarSuccess(res, file) {
            this.addFormData.img = res.data;
        },
        //上传图片前的判断
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    },
    mounted(){
        this.findDish();
        this.findDetailCategory();
    },
    computed: {
        headers() {
            return {
                "Authorization": localStorage.getItem("token")
            }
        }
    },
    watch: {
        //判断批量删除按钮是否禁用
        selectData(newVal, oldVal){ 
            // console.log(newVal)
            // console.log(newVal.length)
            if (newVal.length == 0){
                // console.log(0)
                this.isSelectBtn = true;
            }else{
                // console.log(1)
                this.isSelectBtn = false;
            }
        }
  }

}
</script>

<style scoped>
@import '@/assets/css/eat/dish.css';
</style>